#include <stdio.h>
#include <string.h>
#include <stddef.h>

size_t escape_string_for_mysql(const char *from, size_t length, char *to, size_t to_length)
{
	const char *to_start = to;
	const char *end, *to_end = to_start + (to_length ? to_length-1 : 2*length);
	int overflow = 0;
	char escape;
	
	for (end = from + length; from < end; from++)
	{
		escape = 0;

		switch (*from) 
		{
		case 0:             /* Must be escaped for 'mysql' */
			escape = '0';
			break;
		case '\n':              /* Must be escaped for logs */
			escape = 'n';
			break;
		case '\r':
		  	escape = 'r';
		  	break;
		case '\\':
		  	escape = '\\';
		  	break;
		case '\'':
		  	escape = '\'';
		  	break;
		case '"':               /* Better safe than sorry */
		  	escape = '"';
		  	break;
		case '\032':            /* This gives problems on Win32 */
		  	escape = 'Z';
		  	break;
		}

		if (escape)
		{
			if (to + 2 > to_end)
			{
				overflow = 1;
				break;
			}
			*to++ = '\\';
			*to++ = escape;
		}
		else
		{
			if (to + 1 > to_end)
			{
				overflow = 1;
				break;
			}
			*to++ = *from;
		}
	}

	*to= 0;
	return overflow ? (size_t) -1 : (size_t) (to - to_start);
}

int main(int argc, char **argv)
{
	char* a = "SELECT * FROM t_user WHERE \\ser_name\t\t=\'abc\'";
	//char a_escaped[200] = { 0 };
	char a_escaped[20] = { 0 };

	escape_string_for_mysql(a, strlen(a), a_escaped, sizeof(a_escaped));
	printf("a:%s\n", a);
	printf("a_escaped:%s\n", a_escaped);

	return 0;
}
